package com.zjeav.lingjiao.ui.personCenter;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.dalimao.corelibrary.view.SelfDialog;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.baseBean.Account;
import com.zjeav.lingjiao.base.baseBean.BaseActivity;
import com.zjeav.lingjiao.base.baseBean.Book;
import com.zjeav.lingjiao.base.baseBean.Province;
import com.zjeav.lingjiao.base.baseBean.Result;
import com.zjeav.lingjiao.base.listener.HttpCallbackListener;
import com.zjeav.lingjiao.base.response.SubjectResponse;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.base.utils.StringUtils;
import com.zjeav.lingjiao.ui.book.MallBookContract;
import com.zjeav.lingjiao.ui.login.LoginActivty;
import com.zjeav.lingjiao.ui.personCenter.view.PersonInfoContract;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.UUID;

import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.SinglePicker;

public class PersonInfoActivity extends BaseActivity implements View.OnClickListener,
        PersonInfoContract.View,MallBookContract.View {
    private TextView name_txt, region_txt, school_txt, birth_txt, age_txt, sex_txt, phone_txt, pw_txt, logout_txt;
    private TextView bindemail_txt;
    private PersonPresenter personPresenter;
    private BookPresenter bookPresenter;
    private Account account; //用戶信息
    private SelfDialog selfDialog;
    private ArrayList<Province> province;
    private String json;

    private ArrayList<String> options1Items = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.person_info_layout);
        init();
    }

    private void init() {
        name_txt = findViewById(R.id.name_txt);
        region_txt = findViewById(R.id.region_txt);
        school_txt = findViewById(R.id.school_txt);
        birth_txt = findViewById(R.id.birth_txt);
        age_txt = findViewById(R.id.age_txt);
        sex_txt = findViewById(R.id.sex_txt);
        phone_txt = findViewById(R.id.phone_txt);
        bindemail_txt = findViewById(R.id.bindemail_txt);
        pw_txt = findViewById(R.id.pw_txt);
        logout_txt = findViewById(R.id.logout_txt);
        name_txt.setOnClickListener(this);
        region_txt.setOnClickListener(this);
        school_txt.setOnClickListener(this);
        sex_txt.setOnClickListener(this);
        birth_txt.setOnClickListener(this);
        age_txt.setOnClickListener(this);
        phone_txt.setOnClickListener(this);
        pw_txt.setOnClickListener(this);
        logout_txt.setOnClickListener(this);
        bindemail_txt.setOnClickListener(this);
        personPresenter = new PersonPresenter(this);
        bookPresenter = new BookPresenter(this);
        personPresenter.getAccount();
        bookPresenter.getRegions();


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.name_txt:
                Intent intent = new Intent(PersonInfoActivity.this,ModifyInfoActivity.class);
                intent.putExtra("type","name");
                startActivityForResult(intent,1);
                break;
            case R.id.region_txt: //地区
               // onAddressPicker(view);

                showPickerView();
                break;
            case R.id.bindemail_txt: //绑定邮箱
                Intent intentemail = new Intent(PersonInfoActivity.this,ModifyInfoActivity.class);
                intentemail.putExtra("type","email");
                startActivityForResult(intentemail,6);
                break;
            case R.id.school_txt: //学校
                Intent intent2 = new Intent(PersonInfoActivity.this,ModifyInfoActivity.class);
                intent2.putExtra("type","school");
                startActivityForResult(intent2,2);
                break;
            case R.id.birth_txt: //出生年月
                onYearMonthDayPicker(view);
                break;
            case R.id.age_txt:
                break;
            case R.id.sex_txt: //性别
                onOptionPicker(view);
                break;
            case R.id.phone_txt: //变更手机号
                if(StringUtils.isNullOrEmpty(phone_txt.getText().toString())){
                    Intent intentnophone = new Intent(this, VerifyMobileActivity.class);
                    intentnophone.putExtra("type","4");
                    startActivityForResult(intentnophone,5);
                }else {
                    Intent intentmodifyphone = new Intent(PersonInfoActivity.this,ChangeMobileActivity.class);
                    intentmodifyphone.putExtra("type","modifyphone");
                    intentmodifyphone.putExtra("phone",phone_txt.getText().toString());
                    startActivityForResult(intentmodifyphone,5);
                }

                break;
            case R.id.pw_txt: //修改密码
                Intent intent3 = new Intent(PersonInfoActivity.this,ModifyPasswordActivity.class);
                intent3.putExtra("titlename","修改密码");
                startActivityForResult(intent3,3);
                break;
            case R.id.logout_txt:
                selfDialog = new SelfDialog(this);
                selfDialog.setTitle("提示");
                selfDialog.setMessage("确定退出登录?");
                selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        selfDialog.dismiss();
                        exitApp();
                        Intent intent = new Intent(PersonInfoActivity.this, LoginActivty.class);
                        startActivity(intent);
                        finish();
                    }
                });
                selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        selfDialog.dismiss();
                    }
                });
                selfDialog.show();
                break;
        }
    }

    /**
     * 获取出生年月
     *
     * @param view
     */
    public void onYearMonthDayPicker(View view) {
        final DatePicker picker = new DatePicker(this);

        Calendar c = Calendar.getInstance();//
        int mYear = c.get(Calendar.YEAR); // 获取当前年份
        int mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        int mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当日期

        picker.setCanLoop(true);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(1900, 01, 01);
        picker.setRangeEnd(2111, 1, 11);
        picker.setSelectedItem(mYear, mMonth, mDay);
        picker.setWeightEnable(true);
        picker.setLineColor(Color.BLACK);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                birth_txt.setText(year + "-" + month + "-" + day);
                requestUpdate();
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }


    /**
     * 性别
     * @param view
     */
    public void onOptionPicker(View view) {
        ArrayList<String> list = new ArrayList<>();
        list.add("女");
        list.add("男");
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(true);//不禁用循环
        picker.setLineVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(8);
        picker.setWheelModeEnable(false);
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(getResources().getColor(R.color.mian_blue));//前四位值是透明度
        picker.setUnSelectedTextColor(getResources().getColor(R.color.gray_text));
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {
            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                sex_txt.setText(item);
                requestUpdate();
            }
        });
        picker.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1 && resultCode ==1){
            String name = data.getExtras().getString("editname","");
            name_txt.setText(name);
            requestUpdate();

        }else if (requestCode==2 && resultCode ==2){
            String school = data.getExtras().getString("editname","");
            school_txt.setText(school);
            requestUpdate();
        } else if (requestCode==5 && resultCode ==5){
            String phone = data.getExtras().getString("editname","");
            phone_txt.setText(phone);
            requestUpdate();
        }else if (requestCode==6 && resultCode ==6){
            String email = data.getExtras().getString("editname","");
            bindemail_txt.setText(email);
            requestUpdate();
        }
    }

    /**
     * 更新请求
     */
    private void requestUpdate(){
        account = new Account();
        account.setName(name_txt.getText().toString());
        account.setBirthday(birth_txt.getText().toString());
        account.setSex(sex_txt.getText().toString());
        account.setAddr(region_txt.getText().toString());
        account.setSchool(school_txt.getText().toString());
        account.setMobile(phone_txt.getText().toString());
        account.setEmail(bindemail_txt.getText().toString());
        personPresenter.upPersonInfo(account, 0);
    }

    @Override
    public void showPersonInfo(Account account) {
        this.name_txt.setText(account.getName());
        this.region_txt.setText(account.getAddr());
        this.school_txt.setText(account.getSchool());
        this.birth_txt.setText(account.getBirthday());
        this.age_txt.setText(account.getGrade());
        this.sex_txt.setText(account.getSex());
        this.phone_txt.setText(account.getMobile());
        this.bindemail_txt.setText(account.getEmail());
    }

    @Override
    public void showMallBooks(ArrayList<Book> list) {

    }

    @Override
    public void getGrades(ArrayList<SubjectResponse> list) {

    }

    @Override
    public void getSubjects(ArrayList<SubjectResponse> list) {

    }

    @Override
    public void showError(Throwable throwable) {
        Toast.makeText(this, ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showRegions(ArrayList<Province> province) {
         json = JSONArray.toJSONString(province);
         this.province = province;

        initJsonData();
    }


    @Override
    public void showUpdate(Result result, int type) {
        Toast.makeText(this, "更新信息成功", Toast.LENGTH_SHORT).show();
    }


    private void showPickerView() {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                region_txt.setText(options1Items.get(options1) + "  "
                        + options2Items.get(options1).get(options2) + "  "
                        + options3Items.get(options1).get(options2).get(options3));

                requestUpdate();

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */

     //   ArrayList<JsonBean> jsonBean = parseData(json);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        for (int s=0;s<province.size();s++){
            options1Items.add(province.get(s).getName());
        }

        for (int i = 0; i < province.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int c = 0; c < province.get(i).getCities().size(); c++) {//遍历该省份的所有城市
                String CityName = province.get(i).getCities().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (province.get(i).getCities().get(c).getName() == null
                        || province.get(i).getCities().get(c).getDistricts().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int m=0;m<province.get(i).getCities().get(c).getDistricts().size();m++){
                        String districts = province.get(i).getCities().get(c).getDistricts().get(m).getName();
                        City_AreaList.add(districts);
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }


}
